#include "common.hpp"
#include "Fifo.hpp"
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <cstring>
#include <unistd.h>

int main()
{
    // 打开文件准备写
    PipeOperator writer(PATH, NAME);
    writer.OpenForWrite();
    sleep(3);
    // 构建key值
    key_t key = ftok(gpathname.c_str(), gprojid);
    if (key < 0)
    {
        ERR_EXIT("ftok");
    }
    std::cout << "ftok success" << std::endl;
    // 创建共享内存
    int shmid = shmget(key, gsize, IPC_CREAT);
    if (shmid < 0)
    {
        ERR_EXIT("shmget");
    }
    std::cout << "shm get success" << std::endl;

    // 将共享内存和进程关联
    void *virtauladdr = shmat(shmid, NULL, 0);
    if ((long long)virtauladdr < 0)
    {
        ERR_EXIT("shmat");
    }
    std::cout << "shmat success" << std::endl;
    // 开始通信，拿到共享内存映射的起始地址开始写即可
    writer.Wakeup();
    char *addr = (char *)virtauladdr;
    const char *data = "i am process A";
    for (int i = 0; i < strlen(data); i++)
    {
        addr[i] = data[i];
    }
    // 写完解除连接并且删除共享内存
    int n = shmdt(virtauladdr);
    if (n < 0)
    {
        ERR_EXIT("shmdt");
    }
    std::cout << "shmdt success" << std::endl;

    // 关掉
    writer.Close();
    return 0;
}